package io.nutz.nutzsite.common.listener;

import io.nutz.nutzsite.common.base.Globals;
import io.nutz.nutzsite.module.sys.services.UserService;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;

/**
 * Created by wizzer on 2018/7/5.
 */
@IocBean
public class WebSessionListener implements SessionListener {
	private static final Log log = Logs.get();
    @Inject
    private UserService userService;

    @Override
    public void onStart(Session session) {

    }
/**
 * 用户主动正常退出，才能触发
 */
    @Override
    public void onStop(Session session) {//退出
    	String onlyone=Globals.getConfig("shiro.session.maxSession");
    	if ("1".equals(onlyone)) {
        	String u=Strings.sNull(session.getAttribute("fcre_uid"));
            if (Strings.isNotBlank(u)) {
            	log.debug("\nsession stop:"+u+"\n");
            	userService.deleteOnlineByUid(u);
            	//userService.update(Chain.make("userOnline", false).add("sessionId", ""), Cnd.where("id", "=", Strings.sNull(session.getAttribute("fcre_uid"))));
            }
        }
    }
/**
 * 用户刷新/访问过期的页面时，才能触发。需要系统主动检查过期
 */
    @Override
    public void onExpiration(Session session) {//会话过期时触发
    	String onlyone=Globals.getConfig("shiro.session.maxSession");
    	if ("1".equals(onlyone)) {
    		String u=Strings.sNull(session.getAttribute("fcre_uid"));
            if (Strings.isNotBlank(u)) {
            	log.debug("\nsession Expiration:"+u+"\n");
            	userService.deleteOnlineByUid(u);
            	//userService.update(Chain.make("userOnline", false).add("sessionId", ""), Cnd.where("id", "=", u));
            }
        }
    }

}
